<?php

namespace App\Http\Controllers;

use App\Models\MyMessage;

use App\Models\MakerActivity;
use App\Models\MakerComment;
use App\Models\MakerProject;
use App\Models\User;
use App\Models\MakerUser;
use App\Http\Libs\Helper_Huanxin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use \DB;
use App\Http\Requests\MakerRequest;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\RedirectResponse;
use App\Models\Maker;
use App\Models\Zone;
use App\User as AppUser;
use App\Models\Notice;

class MakerController extends CommonController
{
    /**
     * 获取创客列表
     *
     */
    public function getList()
    {
        $lists = DB::table('maker')
            ->orderBy('maker.id', 'asc')
            ->leftjoin(
                'maker_user',
                function ($join) {
                    $join->on('maker_user.maker_id', '=', 'maker.id')->where('maker_user.is_leader', '=', 1);
                }
            )
            ->leftjoin('user', 'maker_user.uid', '=', 'user.uid')
            ->select('maker.name','maker.maker_type', 'user.nickname', 'user.realname', 'maker.status', 'maker.id', 'maker.if_store', 'maker.recommend', 'maker.email')
            ->paginate(10);

        return view('maker.list')->with("lists", $lists)->with("actions", $this->actions);
    }

    /**
     * 执行一个搜索
     */
    public function search(Request $request)
    {
        $data = $request->input();

        $sql = DB::table('maker')
            ->leftjoin(
                'maker_user',
                function ($join) {
                    $join->on('maker_user.maker_id', '=', 'maker.id')->where('maker_user.is_leader', '=', 1);
                }
            )
            ->leftjoin('user', 'maker_user.uid', '=', 'user.uid')
            ->orderBy('maker.id', 'asc')->select('maker.name','maker.maker_type',  'user.nickname', 'user.realname', 'maker.status', 'maker.id', 'maker.if_store', 'maker.recommend', 'maker.email');

        if (isset($data['name']) && $data['name'] != '') {
            $sql->where('maker.name', 'like', '%' . $data['name'] . '%');
        }

        if (isset($data['nickname']) && $data['nickname'] != '') {
            $sql->orWhere('user.nickname', 'like', '%' . $data['nickname'] . '%');
        }

        if (isset($data['if_store']) && $data['if_store'] != '') {
            $sql->where('maker.if_store', $data['if_store']);
        }

        if (isset($data['recommend']) && $data['recommend'] != '') {
            $sql->where('maker.recommend', $data['recommend']);
        }

        $lists = $sql->paginate(10);

        return view('maker.search')->with("lists", $lists)->with("name", $data['name'])
            ->with("nickname", $data['nickname'])->with("if_store", $data['if_store'])->with("recommend", $data['recommend'])->with("actions", $this->actions);
    }

    /**
     * 获取成员管理界面
     */
    public function getManageMembers(Request $request)
    {
        $id = $request->input('id');

        $users = DB::table('maker_user')
            ->where('maker_user.maker_id', '=', $id)
            ->leftjoin('user', 'maker_user.uid', '=', 'user.uid')
            ->select('maker_user.is_leader', 'user.*')
            ->orderBy('maker_user.is_leader', 'desc')
            ->paginate(10);

        $actions = AppUser::getPermissionAction(10001, 1);

        return view('maker.manage_members')->with('users', $users)->with('maker_id', $id)->with("actions", $actions);
    }

    /**
     * 将一名普通成员设置成管理员
     */
    public function postSetLeader(Request $request)
    {
        $uid = $request->input('uid');
        $maker_id = $request->input('maker_id');

        $user = DB::table('maker_user')
            ->where('maker_id', '=', $maker_id)
            ->where('maker_user.uid', '=', $uid)
            ->first();
        if (empty($user)) {
            return AjaxCallbackMessage('该会员不属于该空间', false);
        }

        DB::table('maker_user')
            ->where('maker_id', $maker_id)
            ->where('is_leader', 1)
            ->update(['is_leader' => 0]);

        DB::table('maker_user')
            ->where('uid', $uid)
            ->where('maker_id', $maker_id)
            ->where('is_leader', 0)
            ->update(['is_leader' => 1]);

        return AjaxCallbackMessage('恭喜，该会员已经被设置为创始人了，原创始人已经自动修改成普通会员了', true);
    }

    /**
     * 删除一名普通成员
     *
     */
    public function postDelMember(Request $request)
    {
        $uid = $request->input('del_uid');
        $maker_id = $request->input('now_maker_id');
        $user = DB::table('maker_user')
            ->where('maker_id', '=', $maker_id)
            ->where('maker_user.uid', '=', $uid)
            ->first();

        if (empty($user)) {
            return AjaxCallbackMessage('该会员不属于该空间', false);
        }

        if ($user->is_leader == 1) {
            return AjaxCallbackMessage('你不能直接删除管理员', false);
        }

        $result = DB::table('maker_user')
            ->where('uid', $uid)
            ->where('maker_id', $maker_id)
            ->where('is_leader', 0)
            ->delete();

        if ($result) {
            return AjaxCallbackMessage('该会员已经成功删除', true);
        } else {
            return AjaxCallbackMessage('删除失败，未知错误,请联系管理员', false);
        }
    }

    /**
     * 显示新增一个会员的界面
     */
    public function getCreateMember(Request $request)
    {
        $maker_id = $request->input('maker_id');

        return view('maker.create_member')->with('maker_id', $maker_id);
    }

    /**
     * 搜寻一个用户以用来作为会员的候选者
     */
    public function candidate(Request $request)
    {
        $data = $request->input();
        $members = DB::table('maker_user')
            ->get();
        $membersId = [];
        foreach ($members as $member) {
            $membersId[] = $member->uid;
        }
        $sql = DB::table('user')
            ->leftJoin('role_user', 'user.uid', '=', 'role_user.uid')
            ->leftJoin('role', 'role.id', '=', 'role_user.role_id')
            ->orderBy('user.uid', 'asc')
            ->whereNotIn('user.uid', $membersId)
            ->select('user.*', 'role_user.role_id', 'role.name');

        if (isset($data['username']) && $data['username'] != '') {
            $sql->where('user.username', 'like', '%' . trim($data['username']) . '%');
        }

        if (isset($data['nickname']) && $data['nickname'] != '') {
            $sql->where('user.nickname', 'like', '%' . trim($data['nickname']) . '%');
        }

        if (isset($data['realname']) && $data['realname'] != '') {
            $sql->where('user.realname', 'like', '%' . trim($data['realname']) . '%');
        }

        if (isset($data['source']) && $data['source'] != '') {
            $sql->where('user.source', $data['source']);
        }
        $users = $sql->paginate(15);
        $actions = AppUser::getPermissionAction(10002, 1);

        return view('maker.candidate')->with("users", $users)->with('maker_id', $data['maker_id'])
            ->with('username', $data['username'])->with('nickname', $data['nickname'])->with('realname', $data['realname'])
            ->with('source', $data['source'])->with('actions', $actions);
    }

    /**
     * 执行新增一名会员
     *
     */
    public function postInsertMember(Request $request)
    {

        $data = $request->input();
        $data['is_leader'] = 0;
        $result = MakerUser::where('uid', $data['uid'])->get();

        if (count($result)) {
            return AjaxCallbackMessage('该用户已经有了所属于的空间了，不能加入第二个空间', false);
        }

        $result = DB::table('maker_user')->insert(['uid' => $data['uid'], 'maker_id' => $data['maker_id'], 'is_leader' => 0]);

        if ($result) {
            $maker = Maker::where('id', $data['maker_id'])->first();
            $user = User::where('uid', $data['uid'])->first();
            $content_sms = trans('sms.makerApplySuccess', array('maker' => $maker->name));
            Notice::create(['title' => '欢迎加入创客空间', 'content' => trans('webNotice.toBeMaker.content'), 'type' => 1, 'uid' => $user->uid]);

            @SendSMS($user->username, $content_sms, 'makerApplySuccess');
            $content_app = trans('app.makerApplySuccess', array('name' => $maker->name, 'kefu' => getKefuName()));
            /***通知客户端刷新***/
            @Helper_Huanxin::sendMessage(array($user->uid), "已成功开通创客空间", "admin", array("type" => "beMakerSuccess_reload"));
            $m_title='恭喜您，您申请的创客空间已经通过审核';
            $m_content='你申请的“创客空间”身份通过无界投融审核并成功获得该身份。';
            $m_ext='<div class="mt10 mb10 dark2_gray">创客空间：<span class="orange">'.$maker->name.'</span></div>
	                <div class="borderLine"></div>
	                <div class="mt10 mb10 dark2_gray">
	   	            <p>你已获得以下权限：</p>
	   	            <div class="lightgray2">
	   	  	        <p>① / 发布活动  所有本地跨域项目均可在平台上发布推广</p>
	   	            <p>② / 参与活动  发现并参与各种本地或跨域活动</p>
	   	            <p>③ / 发起路演  您可以提交路演项目，参加无界投融举办的覆盖全国的跨域项目路演活动 - 无界路演</p>
                    <p>④ / 加入无界投融天涯云计划，实现全球共联</p>
	   	            </div>
	                </div>
	                <div class="borderLine"></div>';
            MyMessage::createMessage($user->uid,$m_title,'official',$m_content,$m_ext,'');
            return AjaxCallbackMessage('添加成功', true, url("maker/candidate?maker_id=$data[maker_id]&username=$data[username]&realname=$data[realname]&nickname=$data[nickname]&source=$data[source]"));
        } else {
            return AjaxCallbackMessage('添加失败，未知错误,请联系管理员', false);
        }
    }

    /**
     * 获取单个空间详情以便编辑
     *
     */
    public function getEdit(Request $request)
    {
        $id = $request->input('id');
        $info = DB::table('maker')
            ->orderBy('maker.id', 'asc')
            ->where('maker.id', '=', $id)
            ->first();

        $members = DB::table('maker_user')
            ->where('maker_user.maker_id', '=', $id)
            ->leftjoin('user', 'maker_user.uid', '=', 'user.uid')
            ->select('maker_user.*', 'user.nickname')
            ->get();

        $leader = null;
        foreach ($members as $key => $member) {
            if ($member->is_leader == 1) {
                $leader = $member;
                unset($members[$key]);
                break;
            }
        }

        $activitys = DB::table('maker_activity')
            ->where('maker_activity.maker_id', '=', $id)
            ->leftjoin('activity', 'maker_activity.activity_id', '=', 'activity.id')
            ->select('maker_activity.*', 'activity.name')
            ->get();
        $orgActivitys = $assActivitys = [];
        foreach ($activitys as $activity) {
            if ($activity->type == 'organizer') {
                $orgActivitys[] = $activity;
            } else {
                $assActivitys[] = $activity;
            }
        }

        $projects = DB::table('maker_project')
            ->where('maker_project.maker_id', '=', $id)
            ->leftjoin('project', 'maker_project.project_id', '=', 'project.id')
            ->select('maker_project.*', 'project.subject')
            ->get();

        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');

        $family = familyTree($zones, $info->zone_id);

//        dd($info);exit;

        return view('maker.edit')->with("info", $info)
            ->with('leader', $leader)->with('members', $members)->with('zoneTree', $zoneTree)->with('family', $family)
            ->with('projects', $projects)->with('orgActivitys', $orgActivitys)->with('assActivitys', $assActivitys);
    }


    public function getInfo(Request $request)
    {
        $id = $request->input('id');
        $info = DB::table('maker')
            ->orderBy('maker.id', 'asc')
            ->where('maker.id', '=', $id)
            ->first();

        $members = DB::table('maker_user')
            ->where('maker_user.maker_id', '=', $id)
            ->leftjoin('user', 'maker_user.uid', '=', 'user.uid')
            ->select('maker_user.*', 'user.nickname')
            ->get();

        $leader = null;
        foreach ($members as $key => $member) {
            if ($member->is_leader == 1) {
                $leader = $member;
                unset($members[$key]);
                break;
            }
        }

        $activitys = DB::table('maker_activity')
            ->where('maker_activity.maker_id', '=', $id)
            ->leftjoin('activity', 'maker_activity.activity_id', '=', 'activity.id')
            ->select('maker_activity.*', 'activity.name')
            ->get();
        $orgActivitys = $assActivitys = [];
        foreach ($activitys as $activity) {
            if ($activity->type == 'organizer') {
                $orgActivitys[] = $activity;
            } else {
                $assActivitys[] = $activity;
            }
        }

        $projects = DB::table('maker_project')
            ->where('maker_project.maker_id', '=', $id)
            ->leftjoin('project', 'maker_project.project_id', '=', 'project.id')
            ->select('maker_project.*', 'project.subject')
            ->get();

        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');

        $family = familyTree($zones, $info->zone_id);


//        dd($info);exit;

        return view('maker.info')->with("info", $info)
            ->with('leader', $leader)->with('members', $members)->with('zoneTree', $zoneTree)->with('family', $family)
            ->with('projects', $projects)->with('orgActivitys', $orgActivitys)->with('assActivitys', $assActivitys);

    }

    /**
     * 编辑一条创客空间信息
     *
     * @return Response
     */
    public function postEdit(MakerRequest $request)
    {
        $data = $request->input();
        unset($data['_token'], $data['formType'], $data['members'], $data['orgActivitys'], $data['assActivitys'], $data['projects'], $data['myfile'], $data['leader'], $data['province_id']);
        if ($data['image'] == '') {
            unset($data['image']);
        }
        $maker = DB::table('maker')
            ->where('id', '=', $data['id'])->first();
        $firstStatus = $maker->status;
//        dd($data);exit;
        $result = DB::table('maker')
            ->where('id', '=', $data['id'])
            ->update($data);
//        dd($data,$result);exit;

        if ($data['status'] && !$firstStatus) {
            $makerUser = MakerUser::whereRaw('maker_id=' . $maker->id . ' and is_leader=1')->first();
            if(count($makerUser)){
                $user = User::where('uid', $makerUser->uid)->first();
                $content_sms = trans('sms.makerApplySuccess', array('name' => $maker->name));
                @SendSMS($user->username, $content_sms, 'makerApplySuccess');
                $content_app = trans('app.makerApplySuccess', array('name' => $maker->name, 'kefu' => getKefuName()));
                @Helper_Huanxin::sendMessage(
                    array($user->uid),
                    $content_app,
                    $from = "admin",
                    $ext = array(
                        'type'    => "hyperjump",
                        'content' => getKefuContentArray()
                    )
                );
            }
        }
        if ($result) {
            return AjaxCallbackMessage('空间编辑成功', true, url('maker/list'));
        } else {
            return AjaxCallbackMessage('空间编辑失败,你没有修改任何内容', false);
        }
    }

    /**
     *显示创建空间的页面
     *
     * @return View
     */
    public function getCreate()
    {
        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');

        return view('maker.create')->with('zoneTree', $zoneTree);
    }

    /**
     * 创建一个空间
     *
     */
    public function postInsert(MakerRequest $request)
    {
        $data = $request->input();

        $username = $data['mobile'];
        if ($data['mobile']) {
            $leader = User::with('roleUser.role')->where('username', $data['mobile'])->first();
            if (!is_object($leader)) {
                return AjaxCallbackMessage('创建空间失败，该手机号没有注册', false);
            }

            if ($leader->roleUser->role->name != '创客空间') {
                return AjaxCallbackMessage('创建空间失败，该用户没有创客身份', false);
            }
        }

        unset($data['_token'], $data['formType'], $data['mobile'], $data['province_id']);

        $data['created_at'] = strtotime("now");
        $data['status'] = 1;
        $result = DB::table('maker')->insertGetId($data);

        if ($username) {
            MakerUser::create(['uid' => $leader->uid, 'maker_id' => $result, 'is_leader' => 1]);
        }

        if ($result) {
            return AjaxCallbackMessage('创建空间成功', true, url('maker/list'));
        } else {
            return AjaxCallbackMessage('创建空间失败', false);
        }
    }

    /**
     * 删除一个空间
     *
     */
    public function postDelete(Request $request)
    {
        $data = $request->input();
        $makerActivity = MakerActivity::where('maker_id', $data['mid'])->get();
        if (count($makerActivity)) {
            return AjaxCallbackMessage('存在与该空间相关联的活动，不能直接删除', false);
        }

        $makerComment = MakerComment::where('maker_id', $data['mid'])->get();
        if (count($makerComment)) {
            return AjaxCallbackMessage('该创客空间下有评论，不能直接删除', false);
        }

        $makerProject = MakerProject::where('maker_id', $data['mid'])->get();
        if (count($makerProject)) {
            return AjaxCallbackMessage('存在与该空间相关联的项目，不能直接删除', false);
        }
        $result = Maker::where('id', $data['mid'])->delete();

        //删除该空间下的成员
        MakerUser::where('maker_id', $data['mid'])->delete();

        if ($result) {
            return AjaxCallbackMessage('删除空间成功', true, url('maker/list'));
        } else {
            return AjaxCallbackMessage('删除空间失败', false);
        }
    }

    /**
     *根据名称模糊搜索一个创客空间
     */
    public function postFind(Request $request)
    {
        $data = $request->input();


        $lists = Maker::where('name', 'like', '%'.$data['name'].'%')->get();
        return AjaxCallbackMessage($lists, true);
    }
}
